import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Gao zhao xu
 * Date: 2023-12-04
 * Time: 上午 08:23
 */
public class Test1 {
    public static int reverseOrder(String s){
        int count = 0;
        for  (int i = 1; i < s.length(); i++){
            int j = i - 1;
            char tmp = s.charAt(i);
            for (;j >= 0;j--){
                if (s.charAt(j) > tmp) count++;
            }
        }
        return count;
    }
    public static void insertSort(int[] arr){
        for  (int i = 1; i < arr.length; i++){
            int j = i - 1;
            int tmp = arr[i];
            for (;j >= 0;j--){
                if (arr[j] > tmp)
                    arr[j + 1] = arr[j];
                else
                    break;
            }
            arr[j + 1] = tmp;
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int m = input.nextInt();
        Map<Integer, String> map = new HashMap<>();
        int[] arr = new int[m];
        input.nextLine();
        for (int i = 0; i < m; i++) {
            String s = input.nextLine();
            arr[i] = reverseOrder(s);
            map.put(arr[i],s);
        }
        insertSort(arr);
        for (int x : arr){
            System.out.println(map.get(x));
        }
    }
}
